<?php

namespace App\Logic;

use App\Model\LiveColumn;
use App\Model\Sign;
use App\Model\User;
use App\Model\UserCoin;
use App\Model\UserIntegral;
use App\Model\UserModelAnchor;
use App\Model\UserModelAssist;
use App\Model\UserModelExpert;
use App\Model\UserTask;
use App\Utils\Enum\UserEnum;
use App\Utils\Log;
use Exception;
use Hyperf\DbConnection\Db;

class AdminUserLogic
{
    /**
     * 用户列表
     * @param $input
     * @return array
     */
    public static function listUser($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = User::query()->when(!empty($input['query']['keyword']), function ($query) use ($input) {
            if (preg_match('/^1\d{10}$/', $input['query']['keyword'])) {
                $query->where('mobile', $input['query']['keyword']);
            } elseif (filter_var($input['query']['keyword'], FILTER_VALIDATE_EMAIL)) {
                $query->where('email', $input['query']['keyword']);
            } else {
                $query->where('username', 'like', "%{$input['query']['keyword']}%");
            }
        })->when(!empty($input['query']['roleId']), function ($query) use ($input) {
            $query->where('role_id', (int)$input['query']['roleId']);
        });
        $total = $query->count();
        if ($total) {
            $records = $query->orderBy('id', 'desc')->limit($pageSize)->offset($offset)->get()->toArray();
            array_walk($records, function (&$v) {
                $v['level'] = UserLogic::getLevelInfo($v['integral'])['curLevelName'];
            });
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 用户详情
     * @param $userId
     * @return array
     * @throws Exception
     */
    public static function detailUser($userId): array
    {
        $user = User::query()->where('id', $userId)->first();
        if (!$user) {
            throw new Exception('用户不存在');
        }
        $user = $user->toArray();
        if ($user['role_id'] == UserEnum::USER_TYPE_EXPERT) {
            $user['extend'] = UserModelExpert::query()->where('userid', $userId)->first()->toArray();
        } elseif ($user['role_id'] == UserEnum::USER_TYPE_ANCHOR) {
            $user['extend'] = UserModelAnchor::query()->where('userid', $userId)->with(['column', 'assistant'])->first()->toArray();
            if (!empty($user['extend']['assistant']) && !empty($user['extend']['assistant']['auto_message'])) {
                $user['extend']['assistant']['auto_message'] = htmlentities(UserModelAssist::query()->where('userid', $user['extend']['assistant_userid'])->value('auto_message'));
            }
            $user['extend']['columns'] = LiveColumn::query()->where('enable', 1)->orderBy('id')->orderBy('listorder')->orderBy('id')->select(['id', 'title', 'image'])->get()->toArray();
        } elseif ($user['role_id'] == UserEnum::USER_TYPE_ASSIST) {
            $user['extend'] = UserModelAssist::query()->where('userid', $userId)->first()->toArray();
            if (!empty($user['extend']['auto_message'])) {
                $user['extend']['auto_message'] = htmlentities($user['extend']['auto_message']);
            }

        }
        return $user;
    }

    /**
     * 修改用户资料
     * @throws Exception
     */
    public static function editUser($userId, $input): true
    {
        $user = User::query()->where('id', $userId)->first();
        if (!$user) {
            throw new Exception('用户不存在');
        }
        $data = [
            'im_id' => $input['imId'],
            'nickname' => $input['nickname'],
            'mobile' => $input['mobile'],
            'email' => $input['email'],
        ];
        if (!empty($input['password'])) {
            $data['salt'] = create_randomstr(6);
            $data['password'] = create_password($input['password'], $data['salt'], false);
        }
        if (User::query()->where('id', '<>', $userId)->where('im_id', $input['imId'])->exists()) {
            throw new Exception('该聊天ID已被占用');
        }
        if (!empty($input['mobile']) && User::query()->where('id', '<>', $userId)->where('mobile', $input['mobile'])->exists()) {
            throw new Exception('该手机号码已被其他账号绑定');
        }
        if (!empty($input['email']) && User::query()->where('id', '<>', $userId)->where('email', $input['email'])->exists()) {
            throw new Exception('该邮箱已被其他账号绑定');
        }

        //检查扩展信息
        if ($user['role_id'] == UserEnum::USER_TYPE_ANCHOR) {
            if (empty($input['extend']['columnId'])) {
                throw new Exception('直播分类错误');
            }
            if (!empty($input['extend']['assistantUserId']) && !User::query()->where(['id' => (int)$input['extend']['assistantUserId'], 'role_id' => UserEnum::USER_TYPE_ASSIST])->exists()) {
                throw new Exception('该助理不存在');
            }
            $extendModel = UserModelAnchor::query();
            $extend = [
                'column_id' => (int)$input['extend']['columnId'],
                'assistant_userid' => (int)$input['extend']['assistantUserId'],
            ];
        } elseif ($user['role_id'] == UserEnum::USER_TYPE_EXPERT) {
            if (empty($input['extend']['expertDesc'])) {
                throw new Exception('专家称号不能为空');
            }
            $extendModel = UserModelExpert::query();
            $extend = [
                'expert_desc' => trim($input['extend']['expertDesc']),
                'introduce' => trim($input['extend']['introduce']),
            ];
        } elseif ($user['role_id'] == UserEnum::USER_TYPE_ASSIST) {
            $extendModel = UserModelAssist::query();
            $extend = [
                'auto_message' => trim($input['extend']['autoMessage']),
            ];
        }

        try {
            User::query()->where('id', $userId)->update($data);
            if (isset($extendModel)) {
                $extendModel->where('userid', $userId)->update($extend);
            }
        } catch (Exception $e) {
            Log::error(sprintf('用户更新异常:%s', $e->getMessage()));
            throw new Exception('修改失败');
        }

        return true;
    }

    /**
     * 升级为助理
     * @param $userId
     * @return true
     * @throws Exception
     */
    public static function upgradeToAssistant($userId): true
    {
        $user = User::query()->where(['id' => $userId, 'role_id' => UserEnum::USER_TYPE_NORMAL])->first();
        if (!$user) {
            throw new Exception('该用户不满足升级条件');
        }
        Db::beginTransaction();
        try {
            User::query()->where('id', $userId)->update(['role_id' => UserEnum::USER_TYPE_ASSIST]);
            UserModelAssist::create([
                'userid' => $user['id'],
                'auto_message' => ''
            ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollBack();
            Log::error(sprintf('升级为助理失败:%s', $e->getMessage()));
            throw new Exception('升级失败');
        }
        return true;
    }

    /**
     * 签到记录
     * @param $input
     * @return array
     */
    public static function logSign($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = Sign::query()->when(!empty($input['query']['keyword']), function ($query) use ($input) {
            $query->where('userid', self::findUserId($input['query']['keyword']));
        })->when(!empty($input['query']['date']), function ($query) use ($input) {
            $query->where('date', date('Ymd', strtotime($input['query']['date'])));
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user'])->limit($pageSize)->offset($offset)->orderBy('id', 'desc')->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 用户任务日志
     * @param $input
     * @return array
     */
    public static function logTask($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = UserTask::query()->when(!empty($input['query']['keyword']), function ($query) use ($input) {
            $query->where('userid', self::findUserId($input['query']['keyword']));
        })->when(!empty($input['query']['date']), function ($query) use ($input) {
            $query->where('date', date('Ymd', strtotime($input['query']['date'])));
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user'])->limit($pageSize)->offset($offset)->orderBy('id', 'desc')->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 金币记录
     * @param $input
     * @return array
     */
    public static function coinRecords($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = UserCoin::query()->when(!empty($input['query']['keyword']), function ($query) use ($input) {
            $query->where('userid', self::findUserId($input['query']['keyword']));
        })->when(!empty($input['query']['direction']), function ($query) use ($input) {
            $query->where('direction', intval($input['query']['direction']));
        })->when(!empty($input['query']['date']), function ($query) use ($input) {
            $query->where('idx_date', date('Ymd', strtotime($input['query']['date'])));
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user'])->orderBy('id', 'desc')->limit($pageSize)->offset($offset)->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 积分记录
     * @param $input
     * @return array
     */
    public static function integralRecords($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = UserIntegral::query()->when(!empty($input['query']['keyword']), function ($query) use ($input) {
            $query->where('userid', self::findUserId($input['query']['keyword']));
        })->when(!empty($input['query']['direction']), function ($query) use ($input) {
            $query->where('direction', intval($input['query']['direction']));
        })->when(!empty($input['query']['date']), function ($query) use ($input) {
            $query->where('idx_date', date('Ymd', strtotime($input['query']['date'])));
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user'])->orderBy('id', 'desc')->limit($pageSize)->offset($offset)->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 查找用户ID
     * @param $keyword
     * @return int
     */
    public static function findUserId($keyword): int
    {
        if (is_mobile($keyword)) {
            $field = 'mobile';
        } elseif (is_email($keyword)) {
            $field = 'email';
        } elseif (preg_match('/^\d+$/', $keyword)) {
            $field = 'im_id';
        } else {
            $field = 'username';
        }
        return (int)User::query()->where($field, $keyword)->value('id');
    }
}